import { SelectProps } from "antd"
import { FC, useEffect, useState } from "react"

import useFundsApi from "@/api/funds"
import { SFormItem } from "@/components/common"
import StyleSelect from "@/components/common/styleSelect"
import { useLocale } from "@/locales"

const SectionCode: FC<any> = ({ rules, selectorProps, setPageOptions }) => {
	const { newFormat } = useLocale()
	const { getAllOptPages } = useFundsApi()
	const [options, setOptions] = useState<SelectProps["options"]>([])
	useEffect(() => {
		;(async () => {
			const [err, data] = await getAllOptPages()
			if (err) {
				setOptions([])
				return
			}
			setOptions(data.map(item => ({ ...item, value: item.sectionCode, label: item.sectionName })))
		})()
	}, [])

	const handleChange = (value?: string) => {
		if (!value) {
			setPageOptions([])
			return
		}
		setPageOptions(
			options?.filter(item => item.value === value).map((item: any) => ({ label: item.pageName, value: item.pageCode }))
		)
	}

	const uniqueSectionOptions = (options || []).reduce((prev, curr) => {
		if (!prev.some((section: any) => section.value === curr.value)) {
			prev.push(curr)
		}
		return prev
	}, [])

	return (
		<SFormItem colon name={"sectionCode"} label={newFormat("common.action_module")} rules={rules}>
			<StyleSelect
				allowClear
				placeholder={newFormat("common.select_all")}
				options={uniqueSectionOptions}
				onChange={handleChange}
				{...selectorProps}
			/>
		</SFormItem>
	)
}

export default SectionCode
